<template>
    <!-- 操作按钮区 -->
    <div class="action-buttons">

      <el-button type="success" @click="batchSaveDetails" class="add-button">添加</el-button>
    </div>
  
    <div>
      <!-- 查询条件部分 -->
      <div class="search-section">
        <el-form :inline="true" :model="prolist">
          <el-form-item label="生产批次号">
            <el-input v-model="prolist.batchNumber" placeholder="输入关联项目"></el-input>
          </el-form-item>
          <el-form-item label="生产日期">
            <el-date-picker v-model="prolist.productionDate" type="date" placeholder="选择日期"></el-date-picker>     
          </el-form-item>
          <el-form-item label="包装类型'">
            <el-input v-model="prolist.packagingType" placeholder="输入领料编号"></el-input>
          </el-form-item>
          <el-form-item label="标签质量">
            <el-input v-model="prolist.labelQuality" placeholder="输入领料主题"></el-input>
          </el-form-item>
          <el-form-item label="密封情况">
            <el-input v-model="prolist.capSealing" placeholder="输入生产线"></el-input>
          </el-form-item>
          <el-form-item label="状况">
            <el-input v-model="prolist.bottleCondition" placeholder="输入检验状态"></el-input>
          </el-form-item>
          <el-form-item label="灌装液位">
            <el-input v-model="prolist.fillLevel" placeholder="输入产品标签"></el-input>
          </el-form-item>

          <el-form-item label="包装材料柔韧性">
            <el-input v-model="prolist.Flexibility" placeholder="输入条形码"></el-input>
          </el-form-item>
          <el-form-item label="包装材料耐水性">
            <el-input v-model="prolist.WaterResistance" placeholder="输入包装人员"></el-input>
          </el-form-item>
          <el-form-item label="包装材料透气性">
            <el-input v-model="prolist.Breathability" placeholder="输入检验人员"></el-input>
          </el-form-item>
          <el-form-item label="包装表面平整度">
            <el-input v-model="prolist.SurfaceFlatness" placeholder="输入管理人员"></el-input>
          </el-form-item>
          <el-form-item label="包装颜色一致性">
            <el-input v-model="prolist.ColorConsistency" placeholder="输入管理人员"></el-input>
          </el-form-item>
          <el-form-item label="质检日期">
            <el-date-picker v-model="prolist.inspectionDate" type="date" placeholder="选择日期"></el-date-picker>     
          </el-form-item>
          <el-form-item label="质检人员姓名">
            <el-input v-model="prolist.inspectorName" placeholder="输入管理人员"></el-input>
          </el-form-item>
          <el-form-item label="质检结果">
            <el-input v-model="prolist.inspectionResult" placeholder="输入管理人员"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button @click="ShowMaterials" class="search-button">查询</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="page-title">
        <h2>包装成品质检列表</h2>
      </div>
      <!-- 生产计划列表（仅展示序号列相关结构） -->
      <div class="table-container">
        <el-table :data="planList" stripe ref="tableRef" style="width: 100%" @selection-change="handleSelectionChange">
          <el-table-column type="selection"></el-table-column>
          <el-table-column prop="id" label="序号"></el-table-column>
          <el-table-column prop="batchNumber" label="包装生产批次号"></el-table-column>
          <el-table-column prop="productionDate" label="包装的生产日期">
            <template #default="scope">
              {{ formatDate(scope.row.productionDate) }}
            </template>
          </el-table-column>
          <el-table-column prop="packagingType" label="包装类型"></el-table-column>
          <el-table-column prop="labelQuality" label="标签质量"></el-table-column>
          <el-table-column prop="capSealing" label="密封情况"></el-table-column>
          <el-table-column prop="bottleCondition" label="包装状况"></el-table-column>
          <el-table-column prop="fillLevel" label="包装灌装液位"></el-table-column>
          <el-table-column prop="flexibility" label="包装材料柔韧性"></el-table-column>
          <el-table-column prop="waterResistance" label="包装材料耐水性"></el-table-column>
          <el-table-column prop="breathability" label="包装材料透气性"></el-table-column>
          <el-table-column prop="surfaceFlatness" label="包装表面平整度"></el-table-column>
          <el-table-column prop="colorConsistency" label="包装颜色一致性"></el-table-column>
          <el-table-column prop="inspectionDate" label="质检日期">
            <template #default="scope">
              {{ formatDate(scope.row.inspectionDate) }}
            </template>
          </el-table-column>
          <el-table-column prop="inspectorName" label="质检人员姓名"></el-table-column>
          <el-table-column prop="inspectionResult" label="质检结果"></el-table-column>
          <el-table-column prop="remarks" label="备注信息"></el-table-column>
          <el-table-column prop="right" label="操作">
            <template #default="scope">
              <el-button type="text" @click="GetBYIdProductionPlanning(scope.row.id)" class="edit-button">编辑</el-button>
              <el-button type="text" @click="DeleteProductionPlanning(scope.row.id)" class="delete-button">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div style="margin-top: 20px">
        <el-pagination
          v-model:current-page="page.pageindex"
          v-model:page-size="page.pageSize"
          :page-sizes="[4, 8, 15, 20]"
          :background="true"
          prev-text="上一页"
          next-text="下一页"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total.totalCount"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, onMounted } from 'vue';
  import { Materialread, Materialwrite } from '@/axios/axiosHelper';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import router from '@/router';
  import axios from 'axios';
  
  // 定义搜索表单数据
  const prolist = ref({
    batchNumber:"",
    productionDate:"",
    packagingType:"",
    labelQuality:"",
    capSealing:"",
    bottleCondition:"",
    fillLevel:"",
    Flexibility:"",
    WaterResistance:"",
    Breathability:"",
    SurfaceFlatness:"",
    ColorConsistency:"",
    inspectionDate:"",
    inspectorName:"",
    inspectionResult:true
 });
  
  // 定义分页总数
  const total = ref({
    totalCount: 0,
    totalPage: 0,
  });
  
  // 定义分页对象
  const page = ref({
    pageindex: 1,
    pageSize: 15,
  });
  
  const formatDate = (dateStr) => {
    const date = new Date(dateStr);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hour = String(date.getHours()).padStart(2, '0');
    const minute = String(date.getMinutes()).padStart(2, '0');
    const second = String(date.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
  };
  
  // 模拟生产计划列表数据
  const planList = ref([
    {
     "id": 0,
      "batchNumber": "",
      "productionDate": "",
      "packagingType": "",
      "labelQuality": "",
      "capSealing": "",
      "bottleCondition": "",
      "fillLevel": "",
      "flexibility": "",
      "waterResistance": "",
      "breathability": "",
      "surfaceFlatness": "",
      "colorConsistency": "",
      "inspectionDate": "",
      "inspectorName": "",
      "inspectionResult": true,
      "remarks": "",
      "isDel": false
    }
  ]);
  
  // 表格引用
  const tableRef = ref(null);
  
  // 全选状态
  const allChecked = ref(false);
  
  // 选中的 ID 列表
  const checkedIds = ref([]);

  const ShowMaterials = () => {
    Materialread.get("p-read/api/CompletedStorage/GetPackagingQualityHandle", {
      params: {
        pageindex: page.value.pageindex,
        pageSize: page.value.pageSize,
        batchNumber: prolist.value.batchNumber,
        productionDate: prolist.value.productionDate,
        packagingType: prolist.value.packagingType,
        labelQuality: prolist.value.labelQuality,
        capSealing: prolist.value.capSealing,
        bottleCondition: prolist.value.bottleCondition,
        fillLevel: prolist.value.fillLevel,
        WaterResistance: prolist.value.WaterResistance,
        Breathability: prolist.value.Breathability,
        SurfaceFlatness: prolist.value.SurfaceFlatness,
        ColorConsistency: prolist.value.ColorConsistency,
        inspectionDate: prolist.value.inspectionDate,
        inspectorName: prolist.value.inspectorName,
        inspectionResult: prolist.value.inspectionResult,
      }
    }).then((res) => {
      planList.value = res.data.data.list;
      console.log("完工入库显示数据", res.data.data);
  
      total.value.totalCount = res.data.data.totalCount;
      total.value.totalPage = res.data.data.totalPage;
      // 重置全选状态和选中的 ID 列表
      allChecked.value = false;
      checkedIds.value = [];
      console.log(res.data.data);
    }).catch((error) => {
      console.error('接口请求失败:', error);
      ElMessage.error('数据获取失败，请稍后重试');
    });
  };
  
  // 编辑跳转修改
  const GetBYIdProductionPlanning = (id) => {
    router.push({
      name: 'UpdatePackagingQuality',
      query: {
        id: id
      }
    }).catch((error) => {
      console.error('路由跳转错误:', error);
      ElMessage.error('跳转失败，请检查');
    });
    console.log(id);
  };
  
  const batchSaveDetails = () => {
    router.push({
      name: 'AddPackagingQuality',
    });
  };
  
//   // 导入
//   const handleImport = () => {
//     Materialread.get("/l-read/api/GetValues/ExportToExce2").then((res) => {
//       ElMessage.success('完工入库导入成功');
//     });
//   };
  
  // 单个删除功能
  // 删除单条记录
  
  const DeleteProductionPlanning = async (id) => {
  try {
    const confirmResult = await ElMessageBox.confirm(
      '确认删除该条记录？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    if (confirmResult === 'confirm') {
      const response = await Materialwrite.post(
        `p-write/api/PackagingQuality/DelPackagingQualit`,
        { id: id.toString() }, // 修改这里，将参数放在请求体中
        {
          params: {id: id.toString()} // 这里保持为空，因为参数已经在请求体中
        }
      );
      if (response.data.code === 200) {
        ElMessage.success('完工质检删除成功');
        ShowMaterials(); // 调用 ShowMaterials 方法刷新数据
      } else {
        ElMessage.error(`完工质检删除失败：${response.data.message}`);
      }
    }
  } catch (error) {
    if (error!== 'cancel') {
      console.error('完工质检删除错误:', error);
      ElMessage.error('完工质检删除失败，请检查网络或联系管理员');
    }
  }
};
  const handleSizeChange = (val) => {
    page.value.pageSize = val;
    ShowMaterials();
  };
  
  const handleCurrentChange = (val) => {
    page.value.pageindex = val;
    ShowMaterials();
  };
  
  onMounted(() => {
    ShowMaterials();
  });
  </script>
  
  <style scoped>
  body {
    font-family: 'Arial', sans-serif;
    background-color: #f0f2f5;
    margin: 0;
    padding: 0;
  }
  
  .action-buttons {
    display: flex;
    justify-content: center;
    padding: 20px;
  }
  
  .import-button,
  .add-button,
  .search-button {
    padding: 10px 20px;
    border-radius: 5px;
    cursor: pointer;
    transition: background-color 0.3s ease;
  }
  
  .import-button {
    border: 1px solid #ccc;
    background-color: white;
    color: #333;
    margin-right: 10px;
  }
  
  .add-button {
    border: none;
    background-color: #42b983;
    color: white;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }
  
  .search-button {
    border: 1px solid #42b983;
    background-color: white;
    color: #42b983;
  }
  
  .search-section {
    background-color: white;
    padding: 8px;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    margin: 0 8px 8px;
  }
  
  .page-title {
    text-align: center;
    color: #2c3e50;
    margin-bottom: 20px;
  }
  
  .table-container {
    background-color: white;
    padding: 20px;
    border-radius: 10px;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.05);
    margin: 0 20px;
    max-height: 400px;
    overflow-y: auto;
  }
  
  .el-table {
    width: 100%;
    border-collapse: collapse;
  }
  
  .el-table__header-wrapper {
    background-color: #f4f4f4;
  }
  
  .el-table__header th {
    padding: 10px;
    text-align: left;
    border-bottom: 1px solid #ccc;
    color: #333;
  }
  
  .el-table__body td {
    padding: 10px;
    border-bottom: 1px solid #eee;
    color: #666;
  }
  
  .edit-button,
  .delete-button {
    color: #42b983;
    padding: 5px 10px;
    border-radius: 5px;
    cursor: pointer;
    transition: background-color 0.3s ease, color 0.3s ease;
  }
  
  .edit-button:hover {
    background-color: #f0f9eb;
  }
  
  .delete-button:hover {
    color: red;
  }
  
  .el-pagination {
    display: flex;
    justify-content: center;
    margin: 20px 0;
  }
  </style>